<template>
  <div>
    <q-card class="my-card" style="margin: 0 12px; padding: 0 50px">
      <div class="row items-center" style="width: 100%">
        <div style="width: 100%">
          <q-card-section class="col-sm-9 col-xs-8 q-px-none">
            <div
              class="row q-gutter-y-sm q-gutter-x-md justify-end"
              style="
                justify-content: space-between;
                width: 100%;
                align-items: center;
              "
            >
              <div class="bg-white q-pa-md">
                <div class="text-h6"><strong>团队设置</strong></div>
              </div>
              <div class="col-md-auto q-pb-sm col-sm gt-sm">
                <q-btn
                  :ripple="false"
                  dense
                  flat
                  style="background: #1890ff; color: white; padding: 0 15px"
                  unelevated
                  icon="add"
                  class="no-border-radius q-px-sm"
                  label="添加人员"
                  @click="addTaskDialog"
                />
              </div>
            </div>
          </q-card-section>
        </div>
      </div>
    </q-card>
    <div class="q-mt-md q-py-md text-grey-8" style="padding: 0 5px">
      <sc-page
        :items="linkManData"
        :datacounts="total"
        :perNumber="pageSize"
        @ChangeCurrentPage="getChangeCurrentPage"
        @ChangeInputPagePage="getChangeInputPagePage"
      >
        <template v-slot:item="props">
          <sc-shadow class="q-mb-md q-mx-md bg-white">
            <q-card class="my-card">
              <q-card-section style="padding: 10px 5px">
                <q-item style="text-align: center">
                  <q-item-section>
                    <q-item-label class="q-mb-md">
                      <q-item-section avatar class="inline-block">
                        <q-avatar style="width: 100px; height: 100px">
                          <img :src="props.item.linkman_pic" />
                        </q-avatar>
                      </q-item-section>
                    </q-item-label>
                    <q-item-label>
                      <q-item-section
                        class="inline-block text-weight-bolder text-body1"
                        v-if="userInfo.isadmin == 0"
                      >
                        {{ props.item.linkman }}
                      </q-item-section>
                      <q-item-section
                        class="inline-block text-weight-bolder text-body1"
                        v-else
                      >
                        {{ props.item.linkman }}({{ props.item.departname }})
                      </q-item-section>
                    </q-item-label>
                    <q-separator spaced="5px" />
                    <q-item-label
                      class="q-mb-sm"
                      style="
                        font-size: 14px;
                        font-weight: bold;
                        padding: 10px 0;
                        margin: 0;
                      "
                    >
                      <span> 联系电话：{{ props.item.mobile }} </span>
                    </q-item-label>
                    <q-item-label
                      class="q-mb-sm"
                      style="font-size: 14px; font-weight: bold; margin: 0"
                    >
                      Q&nbsp;Q：{{ props.item.qq }}
                    </q-item-label>
                    <q-item-label>
                      <q-img
                        :src="props.item.weixin_pic"
                        class="q-mt-sm"
                        style="height: 130px"
                      />
                    </q-item-label>
                    <q-item class="q-px-sm" style="justify-content: center">
                      <q-btn-group flat spread class="full-width">
                        <q-btn
                          flat
                          dense
                          icon="edit"
                          size="sm"
                          color="grey-6"
                          class="q-mx-sm"
                          @click="editItem(props.item)"
                        >
                          <q-tooltip>编辑</q-tooltip>
                        </q-btn>

                     
                        <q-btn
                          flat
                          dense
                          :icon="props.item.isenable? 'subtitles' : 'subtitles_off'"
                          size="sm"
                          color="red"
                          class="q-mx-sm"
                          @click="removeItem(props.item)"
                        >
                          <q-tooltip>注销</q-tooltip>
                        </q-btn>
                        <q-btn
                          flat
                          dense
                          icon="delete"
                          size="sm"
                          color="grey-6"
                          class="q-mx-sm"
                          @click="deleteItem(props.item)"
                        >
                          <q-tooltip>删除</q-tooltip>
                        </q-btn>
                      </q-btn-group>
                    </q-item>
                  </q-item-section>
                </q-item>
              </q-card-section>
            </q-card>
          </sc-shadow>
        </template>
      </sc-page>
    </div>
    <q-dialog
      v-model="addTask"
      fullscreen
      @escape-key="diahide"
      @hide="diahide"
      no-backdrop-dismiss
    >
      <q-card style="width: 45%; max-width: inherit" square class="q-pb-md">
        <q-card-section
          class="row items-center"
          style="background-color: #1890ff; color: #fff; padding-left: 40px"
        >
          <div class="text-h6">{{ task_title }}</div>
          <q-space />
          <q-btn icon="close" flat round dense v-close-popup />
        </q-card-section>
        <form
          ref="addDataForm"
          @submit.prevent.stop="onSubmit"
          @reset.prevent.stop="onReset"
        >
          <q-card-section class="row justify-center">
            <div class="col-sm-12 col-xs-12 q-gutter-md">
              <q-input
                class="q-pb-none"
                ref="title"
                placeholder="请输入部门"
                outlined
                v-model="waitEdit.departname"
                dense
                square
                clearable
              >
                <template v-slot:before>
                  <div class="text_name">部门</div>
                </template>
              </q-input>
              <q-input
                class="q-pb-none"
                ref="title"
                placeholder="请输入姓名"
                outlined
                v-model="waitEdit.linkman"
                dense
                square
                clearable
              >
                <template v-slot:before>
                  <div class="text_name">姓名</div>
                </template>
              </q-input>
              <q-input
                class="q-pb-none"
                ref="title"
                placeholder="请输入手机号"
                outlined
                v-model="waitEdit.mobile"
                dense
                square
                clearable
                :rules="[
                  (val) => (val && val.length == 11) || '请检查手机号是否正确'
                ]"
              >
                <template v-slot:before>
                  <div class="text_name">手机号</div>
                </template>
              </q-input>
              <q-input
                class="q-pb-none"
                placeholder="请输入QQ"
                outlined
                v-model="waitEdit.qq"
                dense
                square
                clearable
              >
                <template v-slot:before>
                  <div class="text_name">QQ号</div>
                </template>
              </q-input>
              <q-input
                class="q-pb-none"
                placeholder="请输入微信名"
                outlined
                v-model="waitEdit.weixin"
                dense
                square
                clearable
              >
                <template v-slot:before>
                  <div class="text_name">微信名</div>
                </template>
              </q-input>
              <q-input
                class="q-pb-none"
                placeholder="请输入关联号码"
                outlined
                v-model="waitEdit.LinkNo"
                dense
                square
                clearable
              >
                <template v-slot:before>
                  <div class="text_name">关联号码</div>
                </template>
              </q-input>

              <div class="col-12 row q-mb-md">
                <span class="text_name">形象照</span>
                <!-- <el-image
                  style="width: 100px; height: 100px"
                  :src="waitEdit.linkman_pic"
                  fit="fill"
                  v-if="isEdit !== '0'"
                ></el-image> -->
                <el-upload
                  class="avatar-uploader"
                  :action="
                    upload_url +
                    '?guestcode=' +
                    waitEdit.guestcode +
                    '&imgpjid=' +
                    waitEdit.pjid
                  "
                  list-type="picture-card"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                >
                  <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </div>
              <div class="col-12 row q-mb-md">
                <span class="text_name">二维码</span>
                <!-- <el-image
                  style="width: 100px; height: 100px"
                  :src="waitEdit.weixin_pic"
                  fit="fill"
                  v-if="isEdit !== '0'"
                ></el-image> -->
                <el-upload
                  class="avatar-uploader"
                  :action="
                    upload_url +
                    '?guestcode=' +
                    waitEdit.guestcode +
                    '&imgpjid=' +
                    waitEdit.pjid
                  "
                  list-type="picture-card"
                  :show-file-list="false"
                  :on-success="handleWeixinPicSuccess"
                  :before-upload="beforeWeixinPicUpload"
                >
                  <img v-if="WeixinPic" :src="WeixinPic" class="avatar" />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </div>

              <div class="text-right">
                <q-btn
                  outline
                  unelevated
                  label="取消"
                  v-close-popup
                  type="reset"
                  class="q-mr-sm no-border-radius"
                  color="grey-6"
                />
                <q-btn
                  unelevated
                  type="submit"
                  label="发布"
                  color="primary"
                  class="no-border-radius"
                  v-if="isEdit == '0'"
                  :loading="loginLoading"
                />
                <q-btn
                  unelevated
                  type="submit"
                  label="保存"
                  color="primary"
                  class="no-border-radius"
                  :loading="loginLoading"
                  v-else
                />
              </div>
            </div>
          </q-card-section>
        </form>
      </q-card>
    </q-dialog>
  </div>
</template>

<script>
import { copyToClipboard } from 'quasar'
import ScShadow from 'components/shadow/ScShadow'
import ScPage from 'components/common/ScPage'
import { getLoginData } from '@/utils/localStorage'
import { getDepartmentApi } from '@/api/cardApi'
import { baseUrl, imgUrl, proUrl } from '@/utils/config'
import { getlinkManApi, GetLinkManDetailApi, linkManApi } from '@/api/cardApi'

export default {
  name: 'UserList',
  components: {
    ScPage,
    ScShadow
  },
  data() {
    return {
      page: 1,
      pageSize: 20,
      total: 0,
      sort: '',
      userInfo: {},
      linkManData: [],
      addTask: false,
      waitEdit: {},
      loginLoading: false,
      isEdit: '',
      fileList: [],
      msg: '上传',
      upload_url: proUrl + '/api/InheartApi/uploadimg',
      imgfileList: [],
      qeditor: '',
      isdatatype: false,
      task_title: '添加',
      isdataicon: 'article',
      imageUrl: '',
      WeixinPic: ''
    }
  },
  methods: {
    copy(item) {
      copyToClipboard(item.mobile)
        .then(() => {
          this.$q.notify({
            color: 'white',
            textColor: 'positive',
            icon: 'check_circle',
            position: 'top-right',
            message: '联系电话【' + item.mobile + '】复制成功'
          })
        })
        .catch(() => {
          // 失败
        })
    },
    getChangeCurrentPage(val) {
      this.getlinkManData(val)
    },
    getChangeInputPagePage(val) {
      this.getlinkManData(val)
    },
    getlinkManData(pageindex) {
      let that = this
      let guestcode = that.userInfo.reguserno
      let gscode = that.userInfo.gscode
      let data = {}
      if (that.userInfo.isadmin == 1) {
        that.sort = 'a.id desc'
      }
      data = {
        guestcode: guestcode,
        gscode: gscode,
        pagesize: that.pageSize,
        pageindex: pageindex,
        sort: that.sort
      }
      getlinkManApi(data).then((res) => {
        if (res.code == 0 && res.data.length > 0) {
          res.data.forEach((element) => {
            if (element.linkman_pic == '') {
              element.linkman_pic =
                'http://www.iqp168.com/src/assets/img/noImg_Default.png'
            } else {
              element.linkman_pic = imgUrl + element.linkman_pic
            }
            if (element.weixin_pic == '') {
              element.weixin_pic =
                'http://www.iqp168.com/src/assets/img/noImg_Default.png'
            } else {
              element.weixin_pic = imgUrl + element.weixin_pic
            }
          })
          that.total = res.dataCount
          that.linkManData = res.data
          // res.depdata.forEach((element) => {
          //   that.departData.push({
          //     departid: element.departid,
          //     departname: element.departname
          //   })
          // })
        } else {
          that.that = []
          that.linkManData = []
        }
      })
    },
    diahide() {
      let that = this
      that.getlinkManData(1)
    },
    //上传
    handleRemove(file, fileList) {
      //console.log(file, fileList)
      let that = this
      let data_imgUrl = ''
      let url = file.response.url + file.response.data
      var index = that.imgfileList.indexOf(url)
      that.imgfileList.splice(index, 1)
      that.imgfileList.forEach((element) => {
        data_imgUrl +=
          element.replace(imgUrl, '').replace('&original=1', '') + ','
      })
      delimgApi({
        guestcode: that.waitEdit.guestcode,
        imgurl: url
      }).then((res) => {
        if (res.code == '0') {
          commonUtil.notifySuccess('删除成功')
        }
      })
    },
    changedata() {
      let that = this
      if (that.isdatatype) {
        that.isdataicon = 'video_library'
      } else {
        that.isdataicon = 'article'
      }
    },
    handlePreview(file) {
      //console.log(file)
    },
    //添加按钮
    addTaskDialog() {
      this.fileList=[]
      this.WeixinPic = undefined
      this.imageUrl = undefined
      this.msg = '点击上传'
      this.isEdit = '0'
      this.waitEdit = {}
      this.addTask = true
      this.qeditor = ''
      this.task_title = '添加联系人'
      this.imgfileList = []
      this.getCurrentTime()
      // console.log(this.userInfo)
      this.waitEdit.guestcode = this.userInfo.reguserno
      this.waitEdit.gscode = this.userInfo.gscode
      this.waitEdit.pjid = this.pjid
    },
    // 编辑
    editItem(item) {
      this.isEdit = '1'
      this.addTask = true
      this.waitEdit = _.clone(item)
      // console.log(this.waitEdit)
      this.qeditor = item.body
      this.task_title = '编辑联系人'
      this.imageUrl = this.waitEdit.linkman_pic
      this.WeixinPic = this.waitEdit.weixin_pic
      this.imgfileList = []
      if (this.waitEdit.inforimg != '' && this.waitEdit.inforimg != undefined) {
        for (var j = 0; j < this.waitEdit.inforimg.split(',').length; j++) {
          this.imgfileList.push(this.waitEdit.inforimg.split(',')[j])
        }
      }
    },
    // 注销
    removeItem(item) {
      let that = this
      that.waitEdit = _.clone(item)
      const addModel = _.clone(that.waitEdit)
      addModel.guestcode = that.userInfo.reguserno
      addModel.gscode = that.userInfo.gscode
      addModel.sType = 'WrittenOff'
      addModel.isenable = false
      that.$q
        .dialog({
          title: '提示',
          message: '是否确认注销?',
          cancel: {
            'text-color': 'black',
            color: 'white',
            label: '取消'
          },
          ok: {
            label: '确定'
          },
          persistent: true
        })
        .onOk(() => {
          linkManApi(addModel).then((res) => {
            if ((res.code = '0')) {
              that.$q.notify({
                color: 'white',
                textColor: 'positive',
                icon: 'check_circle',
                position: 'top',
                message: '注销成功'
              })
              that.getlinkManData(1)
            }
          })
        })
        .onCancel(() => {})
    },
    //删除
    deleteItem(item) {
      let that = this
      that.waitEdit = _.clone(item)
      const addModel = _.clone(that.waitEdit)
      addModel.guestcode = that.userInfo.reguserno
      addModel.gscode = that.userInfo.gscode
      addModel.sType = 'Delete'
      that.$q
        .dialog({
          title: '提示',
          message: '是否确认删除?',
          cancel: {
            'text-color': 'black',
            color: 'white',
            label: '取消'
          },
          ok: {
            label: '确定'
          },
          persistent: true
        })
        .onOk(() => {
          linkManApi(addModel).then((res) => {
            if ((res.code = '0')) {
              that.$q.notify({
                color: 'white',
                textColor: 'positive',
                icon: 'check_circle',
                position: 'top',
                message: '删除成功'
              })
              that.getlinkManData(1)
            }
          })
        })
        .onCancel(() => {})
    },
    //注销
    WrtittOffItem(item) {
      let that = this
      that.waitEdit = _.clone(item)
      const addModel = _.clone(that.waitEdit)
      addModel.guestcode = that.userInfo.reguserno
      addModel.gscode = that.userInfo.gscode
      addModel.sType = 'WrtittOff'
      addModel.isenable = false
      that.$q
        .dialog({
          title: '提示',
          message: '是否确认删除?',
          cancel: {
            'text-color': 'black',
            color: 'white',
            label: '取消'
          },
          ok: {
            label: '确定'
          },
          persistent: true
        })
        .onOk(() => {
          linkManApi(addModel).then((res) => {
            if ((res.code = '0')) {
              that.$q.notify({
                color: 'white',
                textColor: 'positive',
                icon: 'check_circle',
                position: 'top',
                message: '注销成功'
              })
              that.getlinkManData(1)
            }
          })
        })
        .onCancel(() => {})
    },
    getCurrentTime() {
      let yy = new Date().getFullYear()
      let mm = new Date().getMonth() + 1
      let dd = new Date().getDate()
      let hh = new Date().getHours()
      let mf =
        new Date().getMinutes() < 10
          ? '0' + new Date().getMinutes()
          : new Date().getMinutes()
      let ss =
        new Date().getSeconds() < 10
          ? '0' + new Date().getSeconds()
          : new Date().getSeconds()
      var code = ''
      var codeLength = 6
      var random = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
      for (var i = 0; i < codeLength; i++) {
        var index = Math.floor(Math.random() * 9)
        code += random[index]
      }
      this.pjid = yy + mm + dd + hh + mf + ss + code
    },
    onReset() {
      this.waitEdit = {}
      this.waitEdit.name = null
      this.waitEdit.startTime = null
      this.waitEdit.desc = null
      this.waitEdit.id = null
      this.waitEdit.state = null
      this.WeixinPic = undefined
      this.imageUrl = undefined
    },

    onSubmit() {
      let that = this
      that.loginLoading = true
      let addModel = {}
      // if (!that.$refs.title.validate()) {
      //   that.loginLoading = false
      //   return
      // }
      // if (!that.$refs.infortype.validate()) {
      //   that.loginLoading = false
      //   return
      // }
      if (that.isEdit == '0') {
        addModel.guestcode = that.userInfo.reguserno
        addModel.gscode = that.userInfo.gscode
        addModel.mobile = that.waitEdit.mobile ?? ''
        addModel.qq = that.waitEdit.qq ?? ''
        addModel.sType = 'Add'
        addModel.weixin = that.waitEdit.weixin ?? ''
        addModel.weixin_pic = that.waitEdit.weixin_pic ?? ''
        addModel.linkman_pic = that.waitEdit.linkman_pic ?? ''
        addModel.departid = that.waitEdit.departid ?? ''
        addModel.linkNo = that.waitEdit.linkNo ?? ''
        linkManApi(addModel).then((res) => {
          if (res.code == '0') {
            that.$q.notify({
              color: 'white',
              textColor: 'positive',
              icon: 'check_circle',
              position: 'top',
              message: '发布成功'
            })
            setTimeout(() => {
              that.getlinkManData(1)
              that.loginLoading = false
              that.addTask = false
            }, 1000)
          } else {
            that.$q.notify({
              color: 'white',
              textColor: 'positive',
              icon: 'check_circle',
              position: 'top',
              message: res.msg
            })
            that.loginLoading = false
          }
        })
      } else {
        addModel = _.clone(that.waitEdit)
        addModel.guestcode = that.userInfo.reguserno
        addModel.gscode = that.userInfo.gscode
        addModel.sType = 'Edite'
        addModel.linkman_pic = that.waitEdit.linkman_pic.substring(6)
        addModel.weixin_pic = that.waitEdit.weixin_pic.substring(6)
        linkManApi(addModel).then((res) => {
          if (res.code == '0') {
            that.$q.notify({
              color: 'white',
              textColor: 'positive',
              icon: 'check_circle',
              position: 'top',
              message: '修改成功'
            })
            setTimeout(() => {
              that.loginLoading = false
              that.addTask = false
              that.getlinkManData(1)
            }, 1000)
          } else {
            that.$q.notify({
              color: 'white',
              textColor: 'positive',
              icon: 'check_circle',
              position: 'top',
              message: res.msg
            })
            that.loginLoading = false
          }
        })
      }
    },
    // 上传
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      this.waitEdit.linkman_pic = file.response.data
      // console.log(this.waitEdit.linkman_pic)
    },
    handleWeixinPicSuccess(res, file) {
      this.WeixinPic = URL.createObjectURL(file.raw)
      this.waitEdit.weixin_pic = file.response.data
      // console.log(this.waitEdit.weixin_pic)
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 5
      this.$q.notify({
        color: 'white',
        textColor: 'positive',
        position: 'top',
        message: '上传中',
        type: 'warning'
      })
      if (!isLt2M) {
        this.$q.notify({
          color: 'white',
          textColor: 'positive',
          position: 'top',
          type: 'negative',
          message: '上传图片大小不能超过 5MB!'
        })
      }
      return isLt2M
    },
    beforeWeixinPicUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 5
      this.$q.notify({
        color: 'white',
        textColor: 'positive',
        type: 'warning',
        position: 'top',
        message: '上传中'
      })
      if (!isLt2M) {
        this.$q.notify({
          color: 'white',
          textColor: 'positive',

          type: 'negative',
          position: 'top',
          message: '上传图片大小不能超过 5MB!'
        })
      }
      return isLt2M
    }
  },
  mounted() {
    const user = getLoginData()
    if (user == null) {
      this.$router.push('/user/login')
      return
    }
    this.userInfo = user
    this.getlinkManData(1)
  }
}
</script>

<style scoped>
.q-img {
  max-width: 150px;
}
#OldButton {
  display: none;
}
:deep(.el-upload-list--picture .el-upload-list__item) {
  width: auto;
}
:deep(.el-upload-list) {
  display: flex;
  flex-wrap: wrap;
}
:deep(.el-upload--picture-card) {
 width: auto;
 height: auto;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
::v-deep .q-mt-md .row > .col-12,
.q-mt-md .row > .col-xs-12 {
  width: 25%;
}
.cursor-pointer {
  margin: 0;
}
.text_name {
  width: 60px;
  text-align: left;
  color: #000;
  font-size: 14px;
}
::v-deep .q-btn {
  font-size: 14px !important;
}
</style>
